package com.oe.code.controller;

import com.oe.code.dao.LagouAuthCodeDao;
import com.oe.code.pojo.LagouAuthCode;
import com.oe.code.service.LdmMailClient;
import com.oe.common.build.ResponseBuilder;
import com.oe.common.resp.LdmResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import java.util.Calendar;
import java.util.Date;


@RestController
public class CodeController {

    @Autowired
    LagouAuthCodeDao lagouAuthCodeDao;

    @Autowired
    LdmMailClient ldmMailClient;


    @RequestMapping(value = "/code/send/{email}")
    public LdmResponse createCode(@PathVariable("email") String email){
        String code = (int)(Math.random()*1000000)+"";
        LagouAuthCode auth  = new LagouAuthCode();
        auth.setCode(code);
        auth.setEmail(email);
        auth.setCreatetime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int minute=calendar.get(Calendar.MINUTE);
        calendar.set(Calendar.MINUTE,minute+1);
        auth.setExpiretime(calendar.getTime());
        lagouAuthCodeDao.save(auth);

        ldmMailClient.sendMail(email,code);

        return  ResponseBuilder.buildResponse(true,"验证码已发至邮箱！",null);
    }


    @RequestMapping(value = "/code/check/{email}/{code}")
    public LdmResponse createCode(@PathVariable("email") String email, @PathVariable("code") String code){

        LagouAuthCode lagouAuthCode = lagouAuthCodeDao.selectOneByCodeAndAndEmail(code, email);
        if(lagouAuthCode==null){
            return ResponseBuilder.buildResponse(false,"验证码不正确！",null);
        }
        long currentTime = System.currentTimeMillis();
        long time = lagouAuthCode.getExpiretime().getTime();
        if(currentTime>time){
            return ResponseBuilder.buildResponse(false,"验证码已过期！",null);
        }
        return ResponseBuilder.buildResponse(true,null,null);
    }
}
